<template>
	<view class="create-match-container">
		<scroll-view class="form-content" scroll-y>
			<!-- 基本信息 -->
			<view class="form-section">
				<view class="section-header">基本信息</view>
				
				<view class="form-item">
					<text class="form-label">比赛名称 *</text>
					<input 
						class="form-input" 
						v-model="formData.title" 
						placeholder="请输入比赛名称"
						maxlength="100"
					/>
				</view>
				
				<view class="form-item">
					<text class="form-label">比赛地点 *</text>
					<input 
						class="form-input" 
						v-model="formData.location" 
						placeholder="请输入比赛地点"
						maxlength="200"
					/>
				</view>
				
				<view class="form-item">
					<text class="form-label">开始时间 *</text>
					<picker mode="datetime" :value="formData.start_date" @change="onStartDateChange">
						<view class="form-input picker-input">
							{{ formData.start_date ? formatDateTime(formData.start_date) : '请选择开始时间' }}
						</view>
					</picker>
				</view>
				
				<view class="form-item">
					<text class="form-label">结束时间</text>
					<picker mode="datetime" :value="formData.end_date" @change="onEndDateChange">
						<view class="form-input picker-input">
							{{ formData.end_date ? formatDateTime(formData.end_date) : '请选择结束时间' }}
						</view>
					</picker>
				</view>
				
				<view class="form-item">
					<text class="form-label">比赛类型 *</text>
					<picker :value="typeIndex" :range="matchTypes" @change="onTypeChange">
						<view class="form-input picker-input">{{ matchTypes[typeIndex] }}</view>
					</picker>
				</view>
				
				<view class="form-item">
					<text class="form-label">比赛级别 *</text>
					<picker :value="levelIndex" :range="matchLevels" @change="onLevelChange">
						<view class="form-input picker-input">{{ matchLevels[levelIndex] }}</view>
					</picker>
				</view>
				
				<view class="form-item">
					<text class="form-label">比赛描述</text>
					<textarea 
						class="form-textarea" 
						v-model="formData.description" 
						placeholder="请输入比赛描述"
						maxlength="1000"
					/>
				</view>
			</view>
			
			<!-- 联系信息 -->
			<view class="form-section">
				<view class="section-header">联系信息</view>
				
				<view class="form-item">
					<text class="form-label">联系人</text>
					<input 
						class="form-input" 
						v-model="formData.contact_person" 
						placeholder="请输入联系人姓名"
						maxlength="50"
					/>
				</view>
				
				<view class="form-item">
					<text class="form-label">联系电话</text>
					<input 
						class="form-input" 
						v-model="formData.contact_phone" 
						placeholder="请输入联系电话"
						maxlength="11"
						type="number"
					/>
				</view>
				
				<view class="form-item">
					<text class="form-label">联系邮箱</text>
					<input 
						class="form-input" 
						v-model="formData.contact_email" 
						placeholder="请输入联系邮箱"
						maxlength="100"
					/>
				</view>
			</view>
			
			<!-- 其他信息 -->
			<view class="form-section">
				<view class="section-header">其他信息</view>
				
				<view class="form-item">
					<text class="form-label">报名截止时间</text>
					<picker mode="datetime" :value="formData.registration_deadline" @change="onDeadlineChange">
						<view class="form-input picker-input">
							{{ formData.registration_deadline ? formatDateTime(formData.registration_deadline) : '请选择报名截止时间' }}
						</view>
					</picker>
				</view>
				
				<view class="form-item">
					<text class="form-label">备注信息</text>
					<textarea 
						class="form-textarea" 
						v-model="formData.additional_notes" 
						placeholder="请输入备注信息"
						maxlength="500"
					/>
				</view>
			</view>
			
			<!-- 建议裁判人数 -->
			<view class="form-section">
				<view class="section-header">
					<text>裁判人数</text>
					<button type="button" class="add-referee-btn" @click="addRefereePosition">+ 添加职位</button>
				</view>
				
				<view class="section-tip">
					<text class="tip-text">💡 此处设置的是职位需求，实际报名不设上限</text>
				</view>
				
				<view v-for="(position, index) in formData.referee_positions" :key="index" class="referee-item">
					<view class="referee-header">
						<text class="referee-title">职位 {{ index + 1 }}</text>
						<button type="button" class="remove-referee-btn" @click="removeRefereePosition(index)">删除</button>
					</view>
					
					<view class="referee-form">
						<view class="form-item">
							<text class="form-label">职位类型</text>
							<picker :value="position.positionIndex || 0" :range="refereePositions" @change="onRefereePositionChange(index, $event)">
								<view class="form-input picker-input">{{ refereePositions[position.positionIndex || 0] }}</view>
							</picker>
						</view>
						
						<view class="form-item">
							<text class="form-label">建议人数</text>
							<input 
								class="form-input" 
								v-model="position.count" 
								placeholder="请输入建议人数"
								type="number"
							/>
						</view>
						
						<view class="form-item">
							<text class="form-label">职位要求</text>
							<input 
								class="form-input" 
								v-model="position.requirements" 
								placeholder="请输入职位要求"
								maxlength="200"
							/>
						</view>
					</view>
				</view>
			</view>
			
			<!-- 提交按钮 -->
			<view class="submit-section">
				<button class="submit-btn draft-btn" @click="submitMatch('draft')" :disabled="submitting">
					{{ submitting && submitType === 'draft' ? '保存中...' : '保存草稿' }}
				</button>
				<button class="submit-btn publish-btn" @click="submitMatch('published')" :disabled="submitting">
					{{ submitting && submitType === 'published' ? '发布中...' : '立即发布' }}
				</button>
			</view>
		</scroll-view>
	</view>
</template>

<script>
const { callFunction } = require('@/utils/request.js')

export default {
	data() {
		return {
			submitting: false,
			submitType: '',
			
			// 表单数据
			formData: {
				title: '',
				location: '',
				start_date: '',
				end_date: '',
				match_type: '足球',
				level: '校级',
				description: '',
				contact_person: '',
				contact_phone: '',
				contact_email: '',
				additional_notes: '',
				registration_deadline: '',
				referee_positions: [
					{ position: '主裁判', count: 1, requirements: '', positionIndex: 0 }
				]
			},
			
			// 选择器数据
			typeIndex: 0,
			matchTypes: ['足球', '篮球', '排球', '乒乓球', '羽毛球', '网球', '田径', '游泳', '其他'],
			
			levelIndex: 0,
			matchLevels: ['校级', '市级', '省级', '国家级', '国际级'],
			
			refereePositions: ['主裁判', '助理裁判', '第四官员', '裁判监督']
		}
	},
	
	onLoad() {
		this.initDateTimeRange()
	},
	
	methods: {
		// 初始化日期时间范围
		initDateTimeRange() {
			// 生成未来30天的日期
			const today = new Date()
			this.dateRange = []
			for (let i = 1; i <= 30; i++) {
				const date = new Date(today.getTime() + i * 24 * 60 * 60 * 1000)
				const month = String(date.getMonth() + 1).padStart(2, '0')
				const day = String(date.getDate()).padStart(2, '0')
				this.dateRange.push(`${date.getFullYear()}-${month}-${day}`)
			}
			
			// 生成时间选项（8:00 - 22:00，间隔30分钟）
			this.timeRange = []
			for (let hour = 8; hour <= 22; hour++) {
				for (let minute = 0; minute < 60; minute += 30) {
					const timeStr = `${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}`
					this.timeRange.push(timeStr)
				}
			}
		},
		
		// 重置表单
		resetForm() {
			this.formData = {
				title: '',
				location: '',
				start_date: '',
				end_date: '',
				match_type: '足球',
				level: '校级',
				description: '',
				contact_person: '',
				contact_phone: '',
				contact_email: '',
				additional_notes: '',
				registration_deadline: '',
				referee_positions: [
					{ position: '主裁判', count: 1, requirements: '', positionIndex: 0 }
				]
			}
			this.typeIndex = 0
			this.levelIndex = 0
			this.dateIndex = 0
			this.timeIndex = 0
		},
		
		// 日期时间选择
		onStartDateChange(e) {
			this.formData.start_date = e.detail.value;
		},
		
		onEndDateChange(e) {
			this.formData.end_date = e.detail.value;
		},
		
		onDeadlineChange(e) {
			this.formData.registration_deadline = e.detail.value;
		},
		
		// 比赛类型选择
		onTypeChange(e) {
			this.typeIndex = e.detail.value
			this.formData.match_type = this.matchTypes[e.detail.value]
		},
		
		// 比赛级别选择
		onLevelChange(e) {
			this.levelIndex = e.detail.value
			this.formData.level = this.matchLevels[e.detail.value]
		},
		
		// 添加裁判职位
		addRefereePosition() {
			this.formData.referee_positions.push({
				position: '主裁判',
				count: 1,
				requirements: '',
				positionIndex: 0
			})
		},
		
		// 删除裁判职位
		removeRefereePosition(index) {
			if (this.formData.referee_positions.length > 1) {
				this.formData.referee_positions.splice(index, 1)
			} else {
				this.handleError('至少需要保留一个裁判职位')
			}
		},
		
		// 裁判职位选择
		onRefereePositionChange(index, e) {
			const positionIndex = e.detail.value
			this.formData.referee_positions[index].positionIndex = positionIndex
			this.formData.referee_positions[index].position = this.refereePositions[positionIndex]
		},
		
		// 表单验证
		validateForm() {
			if (!this.formData.title.trim()) {
				this.handleError('请输入比赛名称')
				return false
			}
			
			if (!this.formData.location.trim()) {
				this.handleError('请输入比赛地点')
				return false
			}
			
			if (!this.formData.start_date) {
				this.handleError('请选择开始时间')
				return false
			}
			
			// 验证开始时间不能是过去时间
			const startTime = new Date(this.formData.start_date)
			const now = new Date()
			if (startTime <= now) {
				this.handleError('开始时间不能早于当前时间')
				return false
			}
			
			// 验证结束时间
			if (this.formData.end_date) {
				const endTime = new Date(this.formData.end_date)
				if (endTime <= startTime) {
					this.handleError('结束时间不能早于开始时间')
					return false
				}
			}
			
			// 验证报名截止时间
			if (this.formData.registration_deadline) {
				const deadline = new Date(this.formData.registration_deadline)
				if (deadline >= startTime) {
					this.handleError('报名截止时间必须早于比赛开始时间')
					return false
				}
			}
			
			// 验证裁判职位
			for (let i = 0; i < this.formData.referee_positions.length; i++) {
				const position = this.formData.referee_positions[i]
				if (!position.count || position.count < 1) {
					this.handleError(`第${i + 1}个职位的人数必须大于0`)
					return false
				}
			}
			
			return true
		},
		
		// 提交比赛
		async submitMatch(status) {
			if (!this.validateForm()) {
				return
			}
			
			this.submitting = true
			this.submitType = status
			
			try {
				// 准备提交数据
				const submitData = {
					...this.formData,
					status: status,
					match_type: this.formData.match_type,
					level: this.formData.level
				}
				
				// 调用云对象创建比赛
				const matchObject = uniCloud.importObject('match-object')
				const result = await matchObject.createMatch(submitData)
				
				if (result.code === 0) {
					uni.showToast({
						title: status === 'draft' ? '草稿保存成功' : '比赛发布成功',
						icon: 'success'
					})
					
					// 返回上一页
					setTimeout(() => {
						uni.navigateBack()
					}, 1500)
				} else {
					this.handleError(result.message || '操作失败')
				}
			} catch (error) {
				this.handleError(error.message || '网络错误，请稍后重试')
			} finally {
				this.submitting = false
				this.submitType = ''
			}
		},
		
		// 格式化日期时间
		formatDateTime(dateTimeString) {
			if (!dateTimeString) return ''
			const date = new Date(dateTimeString)
			const year = date.getFullYear()
			const month = String(date.getMonth() + 1).padStart(2, '0')
			const day = String(date.getDate()).padStart(2, '0')
			const hour = String(date.getHours()).padStart(2, '0')
			const minute = String(date.getMinutes()).padStart(2, '0')
			return `${year}-${month}-${day} ${hour}:${minute}`
		},
		
		// 错误处理
		handleError(message) {
			uni.showToast({
				title: message,
				icon: 'none'
			})
		}
	}
}
</script>

<style lang="scss" scoped>
.create-match-container {
	min-height: 100vh;
	background-color: #f5f5f5;
}

.form-content {
	height: 100vh;
	padding: 30rpx;
}

.form-section {
	background-color: #fff;
	border-radius: 16rpx;
	padding: 30rpx;
	margin-bottom: 20rpx;
}

.section-header {
	font-size: 28rpx;
	font-weight: bold;
	color: #333;
	margin-bottom: 20rpx;
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.add-referee-btn {
	padding: 8rpx 16rpx;
	background-color: #1BAE76;
	color: #fff;
	border-radius: 20rpx;
	font-size: 24rpx;
	border: none;
}

.form-item {
	margin-bottom: 24rpx;
}

.form-label {
	display: block;
	font-size: 28rpx;
	color: #333;
	margin-bottom: 12rpx;
}

.form-input,
.form-textarea {
	width: 100%;
	padding: 24rpx;
	border: 1px solid #e0e0e0;
	border-radius: 12rpx;
	font-size: 28rpx;
	color: #333;
	background-color: #fff;
	box-sizing: border-box;
}

.picker-input {
	color: #333;
	display: flex;
	align-items: center;
	min-height: 44rpx;
}

.form-textarea {
	min-height: 120rpx;
	resize: none;
}

.referee-item {
	background-color: #f8f8f8;
	border-radius: 12rpx;
	padding: 20rpx;
	margin-bottom: 20rpx;
}

.referee-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 20rpx;
}

.referee-title {
	font-size: 26rpx;
	font-weight: bold;
	color: #333;
}

.remove-referee-btn {
	padding: 8rpx 16rpx;
	background-color: #ff3b30;
	color: #fff;
	border-radius: 16rpx;
	font-size: 22rpx;
	border: none;
}

.submit-section {
	display: flex;
	gap: 20rpx;
	padding-top: 30rpx;
}

.submit-btn {
	flex: 1;
	height: 88rpx;
	border-radius: 12rpx;
	font-size: 32rpx;
	font-weight: bold;
	border: none;
	
	&.draft-btn {
		background-color: #f0f0f0;
		color: #666;
	}
	
	&.publish-btn {
		background: linear-gradient(135deg, #1BAE76 0%, #17a86b 100%);
		color: #fff;
	}
}

.submit-btn[disabled] {
	opacity: 0.6;
}

.section-tip {
	margin-bottom: 20rpx;
	padding: 16rpx 20rpx;
	background: #fff3cd;
	border-radius: 12rpx;
	border-left: 6rpx solid #ffc107;
}

.tip-text {
	font-size: 24rpx;
	color: #856404;
	line-height: 1.4;
}
</style> 
 